package threadandhandler.demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class ThreadAndHandlerActivity extends Activity {
	Button btnStartThread = null;
	Button btnEndThread = null;
	Handler handler = new Handler();
	
	Button btnStartProgressBar = null;
	Button btnEndProgressBar = null;
	ProgressBar progressBar = null;
	
	Button btnThreadDeep = null;
	
	Handler progressBarHandler = new Handler() {
		public void handleMessage(Message msg) {
			progressBar.setProgress(msg.arg1);
			progressBarHandler.post(updateProgressBar);
		}
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btnStartThread = (Button)this.findViewById(R.id.btnStartThread);
        btnEndThread = (Button)this.findViewById(R.id.btnEndThread);  
        
        progressBar = (ProgressBar)this.findViewById(R.id.pbar);
        btnStartProgressBar = (Button)this.findViewById(R.id.btnStartProgressBar);
        btnEndProgressBar = (Button)this.findViewById(R.id.btnEndProgressBar);
        
        btnThreadDeep = (Button)this.findViewById(R.id.btnThreadDeep);
        
        btnStartThread.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				handler.post(updateThread);		
			}
		});
        
        btnEndThread.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				handler.removeCallbacks(updateThread);				
			}
		});
        
        btnStartProgressBar.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				progressBar.setVisibility(View.VISIBLE);
				progressBarHandler.post(updateProgressBar);
			}
		});
        
        btnThreadDeep.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent intent = new Intent(ThreadAndHandlerActivity.this, ThreadDeepActivity.class);
				ThreadAndHandlerActivity.this.startActivity(intent);
			}
		});
    }

    Runnable updateThread = new Runnable(){

		public void run() {
			Log.v("Handler Log", "updateThread");
			handler.postDelayed(updateThread, 3000);
		}
    	
    };
    
    Runnable updateProgressBar = new Runnable(){
    	int i = 0;
		public void run() {
			Log.v("Handler Log", "updateProgressBar");
			
			i += 10;
			Message msg = progressBarHandler.obtainMessage();
			msg.arg1 = i;
			
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			progressBarHandler.sendMessage(msg);
			if (i == 100) {
				progressBarHandler.removeCallbacks(updateProgressBar);
			}
		}
    	
    };
}